#include "http_io.h"

//
// Created by TATO on 2025/8/28.
//
int _http_listen_event_io_do(struct http_socket_event_s *hset);

void socket_fd_handler(event_container_t *ec, event_p_t *e_param);
void connect_fd_handler(event_container_t *ec, event_p_t *e_param);

void http_listen_start_io(http_socket_event_t *hset) {
    // IO模型调用
    _http_listen_event_io_do(hset);
}

int _http_listen_event_io_do(struct http_socket_event_s *hset) {
    struct event_container_s ev_container;
    ev_container.logs = hset->logs;
    ev_container.max_link = MAX_CLINE;
    ev_container.tvp = NULL;
    ev_container.status = 0;
    hset->ev_container = &ev_container;

    init_listen(hset);
    init_conn_fd(hset);
    init_lock(&hset->ev_c_lock);
    init_event_io(hset->ev_container);
    create_event_io(hset->ev_container);
    for(int i = 0;i < sizeof(hset->socket_fd) / sizeof(struct http_server_socket_fd_s);i++){
        if(hset->socket_fd[i].fd) {
            s_add_event(hset->ev_container, &hset->ev_c_lock, hset->socket_fd[i].fd, IO_ADD_RD_EVENT, socket_fd_handler,
                        hset, -1);
            triggerIo(hset->ev_container);
        }
    }
    io_cycle(hset->ev_container);
}

// 处理客户端发送来的数据
void socket_fd_handler(event_container_t *ec, event_p_t *e_param) {
    http_socket_event_handle_t *handler = (http_socket_event_handle_t *) http_malloc(sizeof(http_socket_event_handle_t));
    int fd = e_param->fd;
    struct http_socket_event_s *hset = ((struct http_socket_event_s *)(e_param->args));
    handler->func_read = hset->hgdefc->temp_func_handler->func_read;
    handler->func_write = hset->hgdefc->temp_func_handler->func_write;
    handler->sin_size = sizeof(struct sockaddr_in);
    handler->hset = hset;
    int conn_fd = get_client_fd(hset, handler, fd);
    if(!conn_fd) return;
    s_add_event(ec, &hset->ev_c_lock, conn_fd, IO_ADD_RD_EVENT, connect_fd_handler, handler, 1);
    triggerIo(ec);
}

// 处理客户端发送来的数据
void connect_fd_handler(event_container_t *ec, event_p_t *e_param) {
    int fd = e_param->fd;
    http_socket_event_handle_t *handler = (struct http_socket_event_s *)e_param->args;
    struct http_socket_event_s *hset = handler->hset;
    socket_callback_func func_read = handler->func_read;
    http_free_null(&handler);
    if(ISNOTNULL(func_read)) {
        func_read(hset, fd);
    }
}